package cdu.javaendwork.Controller.Admin.Goods;

import cdu.javaendwork.dao.Universal;
import cdu.javaendwork.dao.impl.UniversalImpl;
import cdu.javaendwork.model.sqlModel.Goods;
import cdu.javaendwork.service.Impl.Shopping.GoodsServiceImpl;
import cdu.javaendwork.service.Interface.Shopping.GoodsService;
import cdu.javaendwork.util.ProNumber.ProNumBerHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

@WebServlet("/admin/goods_add")
public class GoodsAddController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("goods_add.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset = utf-8");
        Goods goods=null;

        //保存照片位置
        String path = "/WEB-INF/goodsPhoto";
        //获取真实对应的地址
        String photoUrl = req.getServletContext().getRealPath(path);
//        System.out.println("photoUrl: " + photoUrl);
        //创建一个基于磁盘文件系统的工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传处理器
        ServletFileUpload upload =new ServletFileUpload(factory);
        try {
            //解析请求
            List<FileItem> items = upload.parseRequest(req);
            if(!items.isEmpty()){
                goods = new Goods();
            }

            //创建迭代器，准备处理表单数据
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()){
                FileItem item = iterator.next();
                if(item.isFormField()){
                    if(item.getFieldName().equals("name")){
                        goods.setName(item.getString("utf-8"));
//                        candidate.setName(new String(item.getString().getBytes("iso-8859-1"),"utf-8"));
                    }
                    if(item.getFieldName().equals("price")){
                        goods.setPrice(new BigDecimal(item.getString("utf-8")));
                    }
                    if(item.getFieldName().equals("description")){
                        goods.setDescription(item.getString("utf-8"));
                    }
                }else {

                    String fileName = item.getName();
                    //防止重复的日期前缀
                    ProNumBerHelper proNumBerHelper = new ProNumBerHelper();
                    String pro = proNumBerHelper.getProNumBerForDate(new Timestamp(new java.util.Date().getTime()).toString());
                    File file = new File(photoUrl+"//"+pro+fileName);
//                    System.out.println("photoUrl+\"//\"+fileName: " + photoUrl+"//"+fileName);
                    item.write(file);
                    goods.setPhoto(req.getContextPath()+path+"/"+pro+fileName);
//                    System.out.println("setphoto: " + goods.getPhoto());
                }
            }
        } catch (Exception e) {
            System.out.println("上传文件出错："+e.getMessage());
        }

        PrintWriter out = resp.getWriter();
        GoodsService goodsService=new GoodsServiceImpl();
        Universal universal=new UniversalImpl();

        Goods goods1=null;
        List<Goods> list = universal.filter("Goods","name='"+goods.getName()+"'");
        if(!list.isEmpty()){
            goods1=list.get(0);
        }

        if(goods.getName()==null||goods.getPrice()==null||goods.getName().equals("")||goods.getPrice().equals("")){
            out.println("<script>alert('新增失败!信息不能为空！');window.location.href='"+req.getContextPath()+"/admin/goods_add'</script>");
        }else if(goods1!=null){
            out.println("<script>alert('新增失败！该商品已存在');window.location.href='"+req.getContextPath()+"/admin/goods_add'</script>");
        } else {
            if(!goodsService.insert(goods.getName(),goods.getPrice(),1,goods.getPhoto(),goods.getDescription())){
                out.println("<script>alert('新增失败！');window.location.href='"+req.getContextPath()+"/admin/goods_add'</script>");
            }else{
                out.println("<script>alert('新增成功！');window.location.href='"+req.getContextPath()+"/admin/goods_list'</script>");
            }
        }
    }
}
